package com.hcq.service;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.common.alimsg.AliMsgService;
import com.common.entity.Rsp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class AliMsgServiceImpl implements AliMsgService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean send(String phoneNumbers, String templateCode, Map<String, Object> code) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4GEyH4qkCxSpd91auuvJ", "4t1Fe1lmgayMc0SW8broGyU4fLUQea");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();

        //不要修改部分
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");

        //自定义参数（手机号，验证码，签名，模板）
        request.putQueryParameter("PhoneNumbers", phoneNumbers);
        request.putQueryParameter("SignName", "sss商城");
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(code));
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断验证码是否过期
     * @param phone
     * @return
     */
    @Override
    public String isExpire(String phone) {
        //获取用户电话号码，查询redis
        return redisTemplate.opsForValue().get(phone);
    }

    /**
     * 生成验证码
     * @return
     */
    public Map<String, Object> createCode() {
        Map<String,Object> map = new HashMap(1);
        String code = ((int) ((Math.random() * 9 + 1) * 100000))+"";
        map.put("code",code);
        return map;
    }


    public Rsp sendResult(String phone,String templateCode) {
        //判断过期
        String redisCode = isExpire(phone);
        if (!StringUtils.isEmpty(redisCode)){
            return Rsp.fail().msg("验证码已发送，请三分钟后再试");
        }

        //生成验证码
        Map<String, Object> code = createCode();
        //发送验证码
        boolean isSend = send(phone, templateCode, code);

        //存入redis
        if(isSend){
            redisTemplate.opsForValue().set(phone, (String) code.get("code"),3*60, TimeUnit.SECONDS);
            return Rsp.success("验证码发送成功，请尽快登录");
        }
        return Rsp.fail().msg("发送失败");
    }
}
